const state = {
  history: Array.isArray(JSON.parse(localStorage.getItem('hi·tory'))) 
    ? JSON.parse(localStorage.getItem('history')) 
    : [],

  currentRequest: {
    method: 'GET',
    url: '',
    params: [],
    body: '',
    headers: []
  },
};

const mutations = {
  ADD_HISTORY(state, record) {
    if (Array.isArray(state.history)) {  
      state.history.push(record);
      localStorage.setItem('history', JSON.stringify(state.history));
    } else {
      console.error('Expected state.history to be an array, but got', typeof state.history);
    }
  },
  REMOVE_HISTORY(state, index) {
    if (Array.isArray(state.history)) {  
      state.history.splice(index, 1);
      localStorage.setItem('history', JSON.stringify(state.history));
    } else {
      console.error('Expected state.history to be an array, but got', typeof state.history);
    }
  },
  SET_HISTORY(state, history) {
    if (Array.isArray(history)) {  
      state.history = history;
      localStorage.setItem('history', JSON.stringify(state.history));  // 保存到 localStorage
    } else {
      console.error('Invalid history data:', history);
    }
  },
  SET_CURRENT_REQUEST(state, request) {
    state.currentRequest = request;
  },
  SET_RESPONSE(state, response) {
    state.currentRequest.response = response;
  },
};

const actions = {
  addHistory({ commit }, record) {
    commit('ADD_HISTORY', record);
  },
  removeHistory({ commit }, index) {
    commit('REMOVE_HISTORY', index);
  },
  setCurrentRequest({ commit }, request) {
    commit('SET_CURRENT_REQUEST', request);
  },
  setResponse({ commit }, response) {
    commit('SET_RESPONSE', response);
  },
};

export default {
  state,
  mutations,
  actions,
};
